from typing import Any, List, Optional

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession

from app.api import deps
from app.crud import message as crud_message
from app.db.session import get_db
from app.schemas.messages import Message, MessageCreate, MessageQuery
from app.services.wechat.wxauto import wxauto_service

router = APIRouter()


@router.get("/sessions", response_model=List[str])
async def get_sessions() -> Any:
    """
    获取会话列表
    """
    sessions = wxauto_service.get_session_list()
    return sessions


@router.get("/messages", response_model=List[Message])
async def get_messages(
    db: AsyncSession = Depends(get_db),
    session_name: Optional[str] = None,
    contact_id: Optional[int] = None,
    limit: int = 50,
    skip: int = 0,
) -> Any:
    """
    获取消息记录
    
    - **session_name**: 会话名称
    - **contact_id**: 联系人ID
    - **limit**: 返回消息数量上限
    - **skip**: 跳过的消息数量
    """
    # 构建查询条件
    query = MessageQuery(
        contact_id=contact_id,
        limit=limit,
        offset=skip
    )
    
    # 从数据库获取消息
    messages = await crud_message.get_messages_by_query(db, query=query)
    
    # 如果指定了会话名称，从wxauto获取消息
    if session_name:
        wxauto_messages = wxauto_service.get_messages(session_name)
        
        # TODO: 将wxauto消息转换为Message格式
        # 这里需要实现将wxauto获取的消息转换为数据库格式的逻辑
        
        # 临时实现：将wxauto消息直接作为Message返回
        return [
            Message(
                id=0,  # 临时ID
                contact_id=None,
                session_id=0,  # 临时会话ID
                direction=msg["direction"],
                msg_type=msg["msg_type"],
                content=msg["content"],
                sent_at=msg["sent_at"],
                status=msg["status"],
                extra_data=None,
                pua_score=None,
                pua_patterns=None
            )
            for msg in wxauto_messages
        ]
    
    return messages


@router.post("/messages", response_model=Message)
async def create_message(
    message_in: MessageCreate,
    db: AsyncSession = Depends(get_db),
) -> Any:
    """
    创建新消息记录
    """
    message = await crud_message.create(db, obj_in=message_in)
    return message


@router.get("/send")
async def send_message(
    session_name: str,
    content: str,
) -> Any:
    """
    发送微信消息
    
    - **session_name**: 会话名称
    - **content**: 消息内容
    """
    result = wxauto_service.send_message(session_name, content)
    if not result:
        raise HTTPException(status_code=400, detail="Failed to send message")
    
    return {"status": "success", "message": "Message sent successfully"}